#include "webServer.hpp"

namespace htmk
{
    
    std::string webServer::m_index_page("\
                                        <html> \
                                        <body> \
                                        <STYLE type='text/css'> \
                                        H1 { text-align: center} \
                                        </STYLE> \
                                        <h1>MASCARA HTML MULTI-SISTEMA LEVANTADA.</h1> \
                                        </body>\
                                        </html>\
                                        ");
    
    webServer::webServer(int port):
	m_daemon(NULL),
	m_port(port)
    
    {
        
    }
    
    webServer::~webServer()
    {
        MHD_stop_daemon (m_daemon);
        std::cout << "Finalizada la conexion con HtmlMask. Salud !" << std::endl;
    }
    
    bool webServer::Run()
    {
        m_daemon = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION, static_cast<uint16_t>(m_port), NULL, NULL, webServer::http_dispatcher, (void*)this, MHD_OPTION_END);
        if (NULL == m_daemon) return false; 
        std::cout << "Escuchando en el puerto 8888, pulse cualquier tecla para finalizar..." << std::endl;
        std::cin.get();     	
        
        return true;
    }
    
    int webServer::http_dispatcher(	void* , struct MHD_Connection* connection, const char* url, const char* method,
                                   const char* version, const char* , size_t* upload_data_size, void** ptr	)
    {	
        static int dummy = 0;
        //const char* page = VP_TO_CCP(cls);	
        struct MHD_Response* response = NULL;
        int ret = 0;
        
        std::cout << "Version : " << version << " " << method << " : " << url << std::endl;
        
        if (std::string(method).compare("GET") != 0)
            return MHD_NO; /* unexpected method */
        
        if (&dummy != *ptr) 
        {
            *ptr = &dummy;
            return MHD_YES;
        }
        
        if (*upload_data_size != 0)
            return MHD_NO; /* upload data in a GET!? */
        
        
        *ptr = NULL; /* clear context pointer */	
        response = MHD_create_response_from_data(m_index_page.size(), CCP_TO_VP(m_index_page.c_str()), MHD_NO, MHD_YES);
        ret = MHD_queue_response(connection, MHD_HTTP_OK, response);
        
        MHD_destroy_response(response);
        
        return ret;
    }
    
}

